<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/10
 * Time: 14:12
 */

namespace app\admin\model;


class CategoryTitle extends DataBase
{
    protected $name = 'category_title';
    protected $autoWriteTimestamp = true;

    public function labelIndexData()
    {
        $page_config = [
            'page' => input('offset', 1),
            'list_rows' => input('limit', 10),
        ];

        $map = [];
        $key = input('key'); $value = input('value');
        if(!empty($key) && !empty($value)) $map[] = [$key,'=',$value];

        $data = $this->where($map)->paginate($page_config);

        foreach($data as $key=>$value){
            $data[$key]['c_name'] = CategoryList::where('id','=',$value['c_id'])->value('name');
        }
        return $data;
    }

    public function labelChangeStatus()
    {
        $id = input('get.id');
        if(empty($id)) return ['code'=>-100,'msg'=>'传参错误'];

        $status = $this->where('id','=',$id)->value('status');
        $status = $status == 1 ? 0 : 1;
        $re = 1;
        if($status == 0){
            $this->startTrans();
            try {
                $res = $this->save(['status'  => $status],['id' => $id]);
                $re = CategoryTitleRoom::where('title_id', '=',$id)->update(['title_id' => 12]);
                $this->commit();

            } catch (\Exception $e) {
                // 回滚事务
                $this->rollback();
            }
        }
        else $res = $this->save(['status'  => $status],['id' => $id]);

        if(!empty($res) && !empty($re)) return ['code'=>100,'msg'=>'修改成功'];
        else return ['code'=>-100,'msg'=>'修改失败'];
    }

    public function labelAdd()
    {
        $newData['pic'] = oosUpload($_FILES['pic'],'qqcategory');
        $newData['name'] = input('name');
        $newData['status'] = input('status');
        $newData['c_id'] = input('c_id');
        $newData['sort'] = input('sort');
        $re = $this->where('name','=',input('name'))->find();
        if(!empty($re)) return ['code'=>-100,'msg'=>'该标签已存在'];
       // halt($newData);
        $res = $this->save($newData);
        if(!empty($res)) return ['code'=>100,'msg'=>'添加成功'];
        else return ['code'=>-100,'msg'=>'添加失败'];
    }
}